#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import threading
import time
import traceback

import pyautogui
from selenium.webdriver.common.by import By
from time import sleep
from base.ObjectMap import ObjectMap
from base.PrintLoginBase import PrintLoginBase
from logs.log import log


class PrintLoginPage(PrintLoginBase, ObjectMap):
    def login_input_value(self, pwd):
        sleep(2)
        print("输入密码")
        length = len(pwd)
        for i in range(length):
            print(pwd[i])
            pyautogui.press(pwd[i])
        # 敲击回车键
        print("回车")
        pyautogui.press('enter')

    def login_click(self, driver):
        log.info("点击登录")
        button_xpath = self.login_button()
        return self.element_click(driver, By.XPATH, button_xpath)

    def input_login_pwd(self, driver, pwd):
        sleep(2)
        print("输入密码")
        # 获取弹框输入密码并确认
        alert = driver.switch_to.alert  # 获取alert对象
        alert.send_keys(pwd)
        alert.accept()

    def to_login(self, driver, url, pwd):
        log.info("跳转登录页面")
        self.element_to_url(driver, url)
        # 使用纯模拟输入
        self.mouse_thread = threading.Thread(target=self.login_input_value, kwargs={"pwd": pwd})
        self.mouse_thread.start()

        # self.mouse_thread = threading.Thread(target=self.input_login_pwd, kwargs={driver: driver, "pwd": pwd})
        # self.mouse_thread.start()

        self.login_click(driver)
        sleep(1)

        # self.login_input_value(pwd)
        # sleep(1)

    def to_print(self, driver, data):
        # @TODO 选择登录用户
        # self.element_click(driver, By.XPATH, "")
        # 预算执行
        # self.element_click(driver, By.XPATH, '//*[@id="pay"]')

        url = driver.current_url
        query = url.split('?')[1]
        new_url = f"https://59.255.67.8/pay/index.html?{query}&appguid=pay#/HomeCard"
        print(f"打开新页面：${new_url}")
        self.element_to_url(driver, new_url)

        time.sleep(0.5)

        # 菜单
        self.element_click(driver, By.XPATH, '//span[text()="菜单"]')
        # 预算执行
        self.element_click(driver, By.XPATH, '//span[contains(text(),"预算执行")]/../../i')
        # 部门支出预算执行
        self.element_click(driver, By.XPATH,
                           '//span[contains(text(),"部门支出预算执行")]/../../i')
        # 国库集中支付
        self.element_click(driver, By.XPATH,
                           '//span[contains(text(),"国库集中支付")]/../../i')
        # 资金支付
        self.element_click(driver, By.XPATH,
                           '//span[contains(text(),"资金支付") and not(contains(text(),"资金支付（内网）"))]/../../i')

        # 集中支付凭证回单接收（预算单位）
        self.element_click(driver, By.XPATH,
                           '//span[contains(text(),"集中支付凭证回单接收（预算单位）")]')
        time.sleep(6)
        # # 已登记
        self.element_click(driver, By.XPATH,
                           '//button[@title="已登记"]')

        time.sleep(5)
        # 获取当前窗口句柄
        current_window = driver.current_window_handle
        # # 获取所有窗口句柄
        all_windows = driver.window_handles
        # # 切换到指定窗口
        # driver.switch_to.window(all_windows[1])
        for handle in all_windows:
            if current_window != handle:
                driver.switch_to.window(handle)
                break
        time.sleep(5)
        # time.sleep(20)
        for i in range(8):
            self.right_click(driver, By.XPATH,
                             '//*[@id="app"]/div/div[3]/div[2]/div/div[1]/div/div[2]/div/div[3]/main/div/div[1]/div[2]/div[3]/div[1]/table/thead/tr/th[2]')
            # 隐藏列
            self.element_click(driver, By.XPATH,
                               "//span[text()='固定列']")
            # 隐藏当前列
            self.element_click(driver, By.XPATH,
                               "//span[text()='清除固定列']")
        for i in range(28):
            self.right_click(driver, By.XPATH,
                             '//*[@id="app"]/div/div[3]/div[2]/div/div[1]/div/div[2]/div/div[3]/main/div/div[1]/div[2]/div[2]/div[1]/table/thead/tr/th[2]')
            # 隐藏列
            self.element_click(driver, By.XPATH,
                               "//span[text()='隐藏列']")
            # 隐藏当前列
            self.element_click(driver, By.XPATH,
                               "//span[text()='隐藏当前列']")
        # 请输入卡号后四位
        count = 0
        for person in data:
            person['images'] = []
            try:
                # print(person['支付申请编号'])
                self.element_click(driver, By.XPATH,
                                   '//span[text()="支付申请编号"]/../span/i[@title="对所选的列启用筛选"]')
                # # #输入内容
                self.element_fill_value1(driver, By.XPATH,
                                         "//input[@placeholder='输入关键字过滤']", person['支付申请编号'], 30)
                time.sleep(1)
                self.element_click(driver, By.XPATH,
                                   "//span[text()='筛选']")
                time.sleep(2)
                rows = len(self.find_element_rows(driver, By.XPATH,
                                                  '//*[@id="app"]/div/div[3]/div[2]/div/div[1]/div/div[2]/div/div[3]/main/div/div[1]/div[2]/div[2]/div[2]/table/tbody/tr'))
                # print(rows)
                # self.assertEqual(person['支付申请编号'],rows,1);#验证是否为1
                # time.sleep(1.5)
                if rows != 1:
                    person['images'].append(self.save_screenshot1(driver))
                    log.info(f"数据：{json.dumps(person)}，找到数据：{rows}，该执行取消")
                    person['success'] = False
                    person['message'] = f"找到数据：{rows}，该执行取消"
                else:
                    # 全选
                    self.element_click(driver, By.XPATH,
                                       '//span[@title="全选/取消"]')

                    time.sleep(1)
                    # 点击打印
                    self.element_click(driver, By.XPATH,
                                       '//button[@title="打印"]')
                    time.sleep(3)
                    # 选择支付凭证打印
                    self.element_click(driver, By.XPATH,
                                       '/html/body/div[7]/div/div[2]/div[1]/div[1]/div[1]/div/label[2]')
                    # # 选择合并打印
                    # self.element_click(driver, By.XPATH,
                    #                    '/html/body/div[7]/div/div[2]/div[1]/div[1]/div[1]/div/label[3]')
                    time.sleep(1)
                    # 点击确认
                    self.element_click(driver, By.XPATH, '//button/span[text()="确定"]')
                    time.sleep(3)
                    # ---------------------------------------选择支付凭证打印------------------------------------
                    # ctrl+p
                    # pyautogui.hotkey("ctrl", "p")
                    driver.switch_to.frame("mergePrintingId")
                    time.sleep(1)
                    self.element_click(driver,By.XPATH,'/html/body/embed')
                    time.sleep(1)
                    # pyautogui.hotkey("ctrl", "s")
                    # time.sleep(1)
                    pyautogui.hotkey("ctrl", "p")
                    # self.element_click(driver, By.XPATH, '//*[@id="toolbar"]/div/div/div/div[3]/div/div/div/div[3]')
                    #
                    time.sleep(1)
                    # driver.switch_to.window(driver.window_handles[-1])
                    # 打印
                    print("回车")
                    pyautogui.press('enter')
                    time.sleep(2)
                    print("关闭前")
                    driver.switch_to.window(driver.window_handles[-1])
                    self.element_click(driver, By.XPATH,
                                       '/html/body/div[7]/div/div[2]/div[1]/div[2]/div/div[1]/button/i')
                    print("关闭后")
                    time.sleep(1)
                    # 取消全选
                    print("取消全选")
                    self.element_click(driver, By.XPATH,
                                       '//span[@title="全选/取消"]')
                    time.sleep(2)
                    # # ----------------------------------------------选择合并打印----------------------------------
                    # # 首先，假设需要在浏览器中模拟点击一个链接
                    # # 先定位链接的位置
                    # link_position = (900, 500)
                    # # 然后模拟鼠标移动到链接位置
                    # pyautogui.moveTo(link_position, duration=1)
                    # # 模拟单次点击
                    # pyautogui.click(clicks=1, interval=1)
                    # # # 等待页面加载完成
                    # # time.sleep(2)
                    # time.sleep(1)
                    # # 获取弹框并确认
                    # # driver.switch_to.alert.accept()
                    # pyautogui.press('enter')
                    # print("回车")
                    # time.sleep(3)
                    # driver.switch_to.window(driver.window_handles[-1])
                    # # 打印弹窗取消
                    # self.element_click(driver, By.XPATH, '//button/span[text()="取消"]')
                    # # /html/body/div[7]/div/div[1]/i
                    # time.sleep(2)
                    # # 取消全选
                    # self.element_click(driver, By.XPATH,
                    #                    '//span[@title="全选/取消"]')
                    person['success'] = True
                    person['message'] = ""
                    count = count + 1
                    person['images'].append(self.save_screenshot1(driver))
            except BaseException as e:
                log.error(traceback.format_exc())
                person['success'] = False
                person['message'] = str(e)
                person['images'].append(self.save_screenshot1(driver))
                pass
            # else:
            #     log.error(traceback)
            #     log.error(traceback.format_exc())
            #     person['success'] = False
            #     person['message'] = traceback.format_exc()
            #     pass
        # sum = len(data)
        # if sum == count:
        #     self.element_click(driver, By.XPATH,
        #                        '//button[@title="未登记"]')
        return data
